package com.youlai.quarkus.system.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.youlai.quarkus.system.common.exception.BusinessException;
import com.youlai.quarkus.system.model.dto.UserAuthInfo;
import com.youlai.quarkus.system.security.model.SysUserDetails;
import com.youlai.quarkus.system.service.SysUserService;
import io.quarkus.security.identity.AuthenticationRequestContext;
import io.quarkus.security.identity.IdentityProvider;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.UsernamePasswordAuthenticationRequest;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.AllArgsConstructor;

import java.util.HashSet;
import java.util.Objects;

@AllArgsConstructor
@ApplicationScoped
public class UsernamePasswordAuthenticationProvider implements IdentityProvider<UsernamePasswordAuthenticationRequest> {

    private final SysUserService sysUserService;

    @Override
    public int priority() {
        return IdentityProvider.super.priority();
    }

    @Override
    public Class<UsernamePasswordAuthenticationRequest> getRequestType() {
        return UsernamePasswordAuthenticationRequest.class;
    }


    /*
            UsernamePasswordAuthenticationRequest
            此外，还需要将quarkus.http.auth.basic=true添加到
            application.properties中，因为标识提供程序与basic auth一起使用。
     */
    @Override
    public Uni<SecurityIdentity> authenticate(UsernamePasswordAuthenticationRequest request,
                                              AuthenticationRequestContext context) {
        String username = request.getUsername();
        UserAuthInfo userAuthInfo = sysUserService.getUserAuthInfo(username);
        if (Objects.isNull(userAuthInfo)) {
            throw new BusinessException("账号密码不正确");
        }
        char[] password = request.getPassword().getPassword();
        if (!BCrypt.checkpw(String.valueOf(password), userAuthInfo.getPassword())) {
            throw new BusinessException("账号密码不正确");
        }
        SysUserDetails details = new SysUserDetails();
        details.setUsername(userAuthInfo.getUsername());
        details.setPassword("");
        details.setEnabled(true);
        details.setPerms(userAuthInfo.getPerms());
        details.setRoles(userAuthInfo.getRoles());
        details.setUserId(userAuthInfo.getUserId());
        details.setDeptId(userAuthInfo.getDeptId());
        details.setDataScope(userAuthInfo.getDataScope());
        QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
        builder.setPrincipal(details).addRoles(new HashSet<>(details.getRoles())).build();
        return Uni.createFrom().item(builder.build());
    }


}
